﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using Intorise.Common;
using Intorise.Net;
using System.Drawing;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using Intorise.API;
using System.Drawing.Imaging;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Model
{
    public class GameHelper
    {
        static ValidateCodeHelper validateCodeHelper = null;
        static string name = null;
        static string sex = null;
        static List<string> nameList = new List<string>();
        static List<string> sexList = new List<string>();
        static List<string> existsList = new List<string>();
        static readonly string LOCAL_CODE_HANDLER = ConfigurationManager.AppSettings["LOCAL_CODE_HANDLER"];

        static GameHelper()
        {
            //validateCodeHelper = new ValidateCodeHelper(AppDomain.CurrentDomain.BaseDirectory + "\\37code.cds");
            try
            {
                validateCodeHelper = new ValidateCodeHelper(AppDomain.CurrentDomain.BaseDirectory + "37code.cds", "zheshijie101");
                using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "姓.txt"))
                {
                    while (!reader.EndOfStream)
                    {
                        sexList.Add(reader.ReadLine());
                    }
                }
                using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "名.txt"))
                {
                    while (!reader.EndOfStream)
                    {
                        nameList.Add(reader.ReadLine());
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleBLL.WriteLineError(ex.Message);
            }
        }

        static string nameCharString = @"获得戛纳年度媒体人物荣誉刘胜义是全球第一位华人刘胜义在中国传媒从业18年其中8年在腾讯度过见证并带领了中国互联网媒体从门户社交到移动发展的黄金年刘胜义指出一直以来世界互联网媒体的标杆都在美国在硅谷但最近几年中国的互联网媒体逐渐地发展起来做出了自己的特色我们正处于中国互联网高速发展的黄金时代我们的目标并不是一味地追求技术革新而是借助技术的力量让千千万万的人都能够平等地享受到数字媒体带来的便利而腾讯新闻腾讯视频等等媒体产品也将继续为他们提供简单易用易获得的内容服务进而用事实还原真相用常识解读新闻民智启迪民智刘胜义说";

        public static string GetSign(string html)
        {
            var tag = "sign:	";
            int index = html.IndexOf(tag);
            if (index > -1)
            {
                index = html.IndexOf("\"", index + tag.Length) + 1;
                return html.Substring(index, 32);
            }
            return "";
        }

        public static string GetTime(string html)
        {
            var tag = "time:       \"";
            int index = html.IndexOf(tag);
            if (index > -1)
            {
                return html.Substring(index + tag.Length, 10);
            }
            return "";
        }

        public static int GetPort(string html)
        {
            var portString = "";
            var tag = "port:";
            int index = html.IndexOf(tag);
            if (index > -1)
            {
                index = html.IndexOf("\"", index + tag.Length) + 1;
                int end = html.IndexOf("\"", index);
                if (end > -1)
                {
                    portString = html.Substring(index, end - index);
                }
            }
            int port = 0;
            int.TryParse(portString, out port);
            return port;
        }

        public static string GetIP(string html)
        {
            var ip = "";
            var tag = "ip:";
            int begin = html.IndexOf(tag);
            if (begin > -1)
            {
                begin = html.IndexOf("\"", begin + tag.Length) + 1;
                int end = html.IndexOf("\"", begin);
                if (end > -1)
                {
                    ip = html.Substring(begin, end - begin);
                }

            }
            return ip;
        }

        public static string GetRandomName(int length = 5)
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            random = new Random(random.Next());
            string name = "";
            for (int i = 0; i < length; i++)
            {
                name += nameCharString[random.Next(nameCharString.Length)];
            }
            return name;
        }

        /// <summary>
        /// 获取2个坐标之间的距离
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public static double GetDistance(Point x, Point y)
        {
            return Math.Sqrt(Math.Pow(Math.Abs(x.X - y.X), 2) + Math.Pow(Math.Abs(x.Y - y.Y), 2));
        }

        public static void RunThreadPool(Action action)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(x =>
            {
                action();
            }));
            thread.IsBackground = true;
            thread.Start();
        }

        public static void RunThread(Action<object> action, object threadObject)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(x =>
            {
                try
                {
                    action(x);
                }
                catch (Exception ex)
                {
                    GameHelper.Handle(ex);
                }
            }));
            thread.IsBackground = true;
            thread.Start(threadObject);
        }

        public static void RunThread(Action action)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(x =>
            {
                try
                {
                    action();
                }
                catch (Exception ex)
                {
                    GameHelper.Handle(ex);
                }
            }));
            thread.IsBackground = true;
            thread.Start();
        }

        public static void Run(Message message, Action<Message> action)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(x =>
            {
                Thread.CurrentThread.IsBackground = true;
                try
                {
                    action((Message)x);
                }
                catch (Exception ex)
                {
                    GameHelper.Handle(ex);
                }
            }), message);
        }

        public static Thread Start(Action<object> action)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(action));
            thread.Start();
            return thread;
        }

        internal static void Handle(Exception ex)
        {
            if (ex is System.Threading.ThreadAbortException)
            {

            }
            else
            {
                ConsoleBLL.WriteLineError("出现异常：\r\n" + ex.Message + "\r\n" + ex.StackTrace);
            }
        }

        public static Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                return bmp;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Base64StringToImage 转换失败/nException：" + ex.Message);
                ConsoleBLL.WriteLineError("图片数据：\r\n" + inputStr);
                return null;
            }
        }

        public static Bitmap StringToImage(string inputStr)
        {
            try
            {
                byte[] arr = Encoding.ASCII.GetBytes(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                return bmp;
            }
            catch (Exception ex)
            {
                MessageBox.Show("StringToImage 转换失败/nException：" + ex.Message);
                ConsoleBLL.WriteLineError("图片数据：\r\n" + inputStr);
                return null;
            }
        }

        internal static string GetCode(Image image)
        {
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            var data = stream.ToArray();
            stream.Close();
            return validateCodeHelper.GetVcode(data);
        }

        internal static string GetLocalCode(byte[] datas)
        {
            var filename = AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid() + ".tmp";
            try
            {
                using (FileStream stream = new FileStream(filename, FileMode.Create))
                {
                    stream.Write(datas, 0, datas.Length);
                    stream.Flush();
                }
                WebClient client = new WebClient();
                client.BaseAddress = LOCAL_CODE_HANDLER;
                var text = Encoding.UTF8.GetString(client.UploadFile(LOCAL_CODE_HANDLER, filename));
                var result = (JObject)JsonConvert.DeserializeObject(text);
                if (result["Success"].ToString() == "True")
                {
                    ConsoleBLL.WriteLineInfo("获取本地验证码：" + result["Code"]);
                    return result["Code"].ToString();
                }
                else
                {
                    ConsoleBLL.WriteLineError("获取本地验证码错误：" + result["Message"]);
                }
            }
            finally
            {
                File.Delete(filename);
            }
            return "";
        }

        public static string GetName()
        {
            var newName = "";
            do
            {
                Random r = new Random((int)DateTime.Now.Ticks);
                newName = sexList[r.Next(sexList.Count)] + nameList[r.Next(nameList.Count)];
                lock (existsList)
                {
                    if (!existsList.Contains(newName))
                    {
                        existsList.Add(newName);
                        break;
                    }
                }
            } while (true);
            return newName;
        }
    }
}